<?php

namespace app\models;
use yii\db\Query;
use Yii;
use yii\base\Model;
use yii\captcha\Captcha;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    public $verifyCode;

    private $_user = false;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
            ['verifyCode', 'captcha', 'on' => 'withCaptcha']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => Yii::t('app', 'Username Or Email'),
            'password' => Yii::t('app', 'Password'),
            'rememberMe' => Yii::t('app', 'Remember Me'),
            'verifyCode' => Yii::t('app', 'Verify Code')
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if ($user && !$user->validatePassword($this->password)) {
                $this->addError('password', Yii::t('app', 'Incorrect password.'));
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $user = $this->getUser();
            // 确保获取到了用户对象
            if ($user === null)  return false;
            return Yii::$app->user->login($user, $this->rememberMe ? 3600 * 24 * 30 : 0);                
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByLoginID($this->username);
            if (!$this->_user) {
                $this->addError('username', Yii::t('app', 'Username does not exist.'));
            }else if($this->_user->status==User::STATUS_DISABLE){
                $this->addError('username', Yii::t('app', 'The user has been disabled.'));
            }else if(Yii::$app->setting->get('isContestUserLogin')){
                if(!$this->canUserLogin($this->user,Yii::$app->setting->get('beforeTime'))){
                    $msg = $this->getErrorMsg(Yii::$app->setting->get('beforeTime'));
                    $this->addError('username', '当前只允许参赛用户在'.$msg.'登录。');
                    $this->_user = false; 
                }
            }
        }
        return $this->_user;
    }

    public function getErrorMsg($time){
        if($time==0) return "比赛开始";
        if($time<60) return "比赛前".$time."分钟";
        return "比赛前".intval($time/60)."小时";
    }

    /**
     * 判断普通用户当天是否有比赛，有比赛则可以登录
     */
    public function canUserLogin($user,$time){
        if($user->role>=User::ROLE_TEACHER) return true;//教师与管理员允许登录

        // 获取当前日期和时间
        $currentDateTime = date('Y-m-d H:i:s');

        // 构建查询条件
        $query = (new Query())
            ->select(['contest.*'])
            ->from('contest')
            ->innerJoin('contest_user', 'contest.id = contest_user.contest_id')
            ->where(['contest_user.user_id' => $user->id])
            ->andWhere(['contest.group_id' => 0])
            ->andWhere(['<=', 'DATE_SUB(contest.start_time, INTERVAL '.$time.' MINUTE)', $currentDateTime])
            ->andWhere(['>=', 'contest.end_time', $currentDateTime]);

        // 执行查询
        $result = $query->all();

        // 判断结果
        if (!empty($result)) {
            return true;
        } else {
            return false;
        }
    }


}
